<template>
  <div class="image-cropper">
    <el-dialog
      title="图片裁切"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleClose"
    >
      <div class="cropper-container">
        <div class="cropper-wrapper">
          <img
            ref="cropperImage"
            :src="imageSrc"
            style="max-width: 100%; max-height: 400px;"
            @load="initCropper"
          />
            </div>

        <div class="cropper-controls">
          <div class="size-info">
            <span>裁切尺寸: {{ cropSize }}x{{ cropSize }}px</span>
            </div>

          <div class="preview-container">
            <div class="preview-label">预览:</div>
            <div 
              class="preview-image"
              :style="{ width: cropSize + 'px', height: cropSize + 'px' }"
            ></div>
            </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCrop">确定裁切</el-button>
          </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ImageCropper',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    imageSrc: {
      type: String,
      required: true
    },
    cropSize: {
      type: Number,
      default: 50
    }
  },
  data() {
    return {
      dialogVisible: false,
      cropper: null
    }
  },
  watch: {
    visible: {
      handler(val) {
        this.dialogVisible = val
      },
      immediate: true
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    initCropper() {
      if (this.cropper) {
        this.cropper.destroy()
      }
      
      this.$nextTick(() => {
        if (this.$refs.cropperImage) {
          // 使用简单的裁切实现
          this.setupSimpleCropper()
        }
      })
    },
    
    setupSimpleCropper() {
      const img = this.$refs.cropperImage
      const container = img.parentElement
      
      // 创建裁切框
      const cropBox = document.createElement('div')
      cropBox.className = 'crop-box'
      cropBox.style.cssText = `
        position: absolute;
        border: 2px solid #409eff;
        background: rgba(64, 158, 255, 0.1);
        cursor: move;
        width: ${this.cropSize}px;
        height: ${this.cropSize}px;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        box-sizing: border-box;
      `
      
      container.style.position = 'relative'
      container.appendChild(cropBox)
      
      // 添加拖拽功能
      this.addDragFunctionality(cropBox, img)
      
      this.cropBox = cropBox
    },
    
    addDragFunctionality(cropBox, img) {
      let isDragging = false
      let startX, startY, startLeft, startTop
      
      cropBox.addEventListener('mousedown', (e) => {
        isDragging = true
        startX = e.clientX
        startY = e.clientY
        const rect = cropBox.getBoundingClientRect()
        const containerRect = img.getBoundingClientRect()
        startLeft = rect.left - containerRect.left
        startTop = rect.top - containerRect.top
        
        document.addEventListener('mousemove', handleMouseMove)
        document.addEventListener('mouseup', handleMouseUp)
      e.preventDefault()
      })
      
      const handleMouseMove = (e) => {
        if (!isDragging) return
        
        const deltaX = e.clientX - startX
        const deltaY = e.clientY - startY
        
        const newLeft = Math.max(0, Math.min(startLeft + deltaX, img.offsetWidth - this.cropSize))
        const newTop = Math.max(0, Math.min(startTop + deltaY, img.offsetHeight - this.cropSize))
        
        cropBox.style.left = newLeft + 'px'
        cropBox.style.top = newTop + 'px'
      }
      
      const handleMouseUp = () => {
        isDragging = false
        document.removeEventListener('mousemove', handleMouseMove)
        document.removeEventListener('mouseup', handleMouseUp)
      }
    },
    
    handleCrop() {
      if (!this.cropBox) {
        this.$message.error('裁切框未初始化')
        return
      }
      
      const img = this.$refs.cropperImage
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      
      // 设置画布尺寸
      canvas.width = this.cropSize
      canvas.height = this.cropSize
      
      // 计算裁切区域
      const rect = this.cropBox.getBoundingClientRect()
      const imgRect = img.getBoundingClientRect()
      
      const cropX = rect.left - imgRect.left
      const cropY = rect.top - imgRect.top
      
      // 计算缩放比例
      const scaleX = img.naturalWidth / img.offsetWidth
      const scaleY = img.naturalHeight / img.offsetHeight
      
      // 裁切图片
      ctx.drawImage(
        img,
        cropX * scaleX,
        cropY * scaleY,
        this.cropSize * scaleX,
        this.cropSize * scaleY,
        0,
        0,
        this.cropSize,
        this.cropSize
      )
      
      // 转换为blob
      canvas.toBlob((blob) => {
        const croppedUrl = URL.createObjectURL(blob)
        this.$emit('cropped', croppedUrl, blob)
        this.dialogVisible = false
      }, 'image/png', 0.9)
    },
    
    handleClose() {
      if (this.cropBox) {
        this.cropBox.remove()
        this.cropBox = null
      }
    }
  },
  
  beforeDestroy() {
    this.handleClose()
  }
}
</script>

<style scoped>
.cropper-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.cropper-wrapper {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #f5f7fa;
}

.cropper-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
}

.size-info {
  font-size: 14px;
  color: #606266;
}

.preview-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.preview-label {
  font-size: 14px;
  color: #606266;
}

.preview-image {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #999;
}

.crop-box {
  position: absolute;
  border: 2px solid #409eff;
  background: rgba(64, 158, 255, 0.1);
  cursor: move;
  box-sizing: border-box;
}

.crop-box::before {
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  border: 1px dashed #409eff;
  pointer-events: none;
}
</style>